/*
 * 个人信息
 * @Author: yudong
 * @Date: 2018-04-04 16:49:50
 * @Last Modified by: ljb
 * @Last Modified time: 2019-05-15 18:39:40
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    @import '~src/assets/css/common.less';
    .v-user-information {
        position: relative;
        width: 100%;
		height: 100%;
		background:linear-gradient(-120deg,rgba(255,242,199,1) 0%,rgba(255,174,204,1) 40%);
        // background-image: url('~src/assets/media/img/user/bg.png');
        // background-size: cover;
		// background-repeat: no-repeat;
		.main{
			position: absolute;
			top: 86*@rem-per-px;
			bottom: 0;
			right: 0;
			left: 0;
			margin: auto;
		}
		.main.iswechat{
			top: 0;
		}
        .form-box {
            width: 670*@rem-per-px;
            max-height: 1034*@rem-per-px;
            padding: 78*@rem-per-px 10*@rem-per-px 10*@rem-per-px 0;
            border-radius: 55*@rem-per-px;
            background-color: #fff;
            text-align: center;
            box-sizing: border-box;
			box-shadow: 0 0 40*@rem-per-px 0 rgba(182,43,85,.3);
			&.focus {
				position: relative;
				margin-top: 5px;
			}
			&.blur {
				position: inherit;
			}
            .form-item {
				position: relative;
                margin-bottom: 34*@rem-per-px;
            }
            input {
                width: 536*@rem-per-px;
                height: 98*@rem-per-px;
                border: 1px solid #e0e0e0;
                border-radius: 50*@rem-per-px;
                outline: 0;
                font-size: 31*@rem-per-px;
				text-align: center;
				line-height: normal;
                -webkit-appearance: none;
                appearance: none;
                &::placeholder {
                    font-size: 31*@rem-per-px;
                    color: rgb(204,204,204);
				}
				&.born {
					user-select:none;
				}
			}
			select {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				width: 536*@rem-per-px;
				height: 98*@rem-per-px;
				margin: 0 auto;
				border: 1px solid #e0e0e0;
				border-radius: 50*@rem-per-px;
				font-size: 31*@rem-per-px;
				background: transparent;
				appearance: none;
				outline: 0;
				opacity: 0;
			}
            .avatar {
                display: flex;
                width: 536*@rem-per-px;
                margin: 36*@rem-per-px auto 70*@rem-per-px;
                justify-content: space-between;
                div {
                    width: 236*@rem-per-px;
                    height: 292*@rem-per-px;
                    border: 1px solid #E8E8E8;
                    border-radius: 30*@rem-per-px;
                    text-align: center;
                    padding-top: 36*@rem-per-px;
                    box-sizing: border-box;
                    &.selected {
                        border: 6*@rem-per-px solid #FFAECC;
                    }
                    img {
                        width: 168*@rem-per-px;
                        height: 168*@rem-per-px;
                        margin-bottom: 30*@rem-per-px;
                    }
                    p {
                        font-size: @main-font;
                    }
                }
            }
            /*提交按钮*/
            .button {
				position: relative;
                width: 534*@rem-per-px;
                height: 98*@rem-per-px;
                color: #fff;
                font-size: @main-font;
                border: none;
                border-radius: 50*@rem-per-px;
                // background: linear-gradient(80deg,rgb(255,174,204,1) 80%,rgb(255,242,199,1) 20%);
                background:linear-gradient(90deg,rgba(255,174,204,1) 80%,rgba(255,242,199,1) 110%);
                box-shadow: 0 0 26*@rem-per-px 0 #FFAECC;
                transition: all .5s 0s ease;
                outline: none;
				&::after {
					content: '';
					position: absolute;
					top: -20px;
					bottom: -20px;
					left: -20px;
					right: -20px;
					background: linear-gradient(to right,rgb(255,174,204,1),rgb(255,242,199,1));
					background-repeat: no-repeat;
					background-position: 50%;
					border-radius: 50*@rem-per-px;
					opacity: 0;
					transition: all .3s;
				}
				&:active::after {
					top: 0;
					bottom: 0;
					left: 0;
					right: 0;
					opacity: .5;
					transition: 0s;
				}
            }
            /*提交按钮 END*/
        }
    }
</style>
<template>
	<div class="v-user-information">
		<back v-if="!is_wechat"/>
		<div
			:class="{iswechat: is_wechat}"
			class="main">
			<div
				ref="form_box"
				:class="{'focus' : focus , 'blur' : !focus }"
				class="form-box level-vertical-middle">
				<div class="form-item">
					<input
						:placeholder="$t('info.name_placeholder')"
						v-model="formvalidate.name"
						type="text"
						name="name"
						@focus="focusEvent"
						@blur="blurEvent">
				</div>
				<div class="form-item">
					<input
						:placeholder="$t('info.phone_placeholder')"
						v-model="formvalidate.phone"
						name="phone"
						type="text"
						@focus="focusEvent"
						@blur="blurEvent">
				</div>
				<div
					class="form-item">
					<select
						id="age_select"
						v-model="formvalidate.age"
						name="age">
						<option
							v-for="age in createAgeArray()"
							:key="age"
							:value="age">{{ age }}</option>
					</select>
					<input
						:placeholder="$t('info.age_placeholder')"
						:value="formvalidate.age + $t('info.years_old')"
						class="born"
						type="text"
						readonly>
				</div>
				<div class="avatar">
					<div
						v-for="sex in sexs"
						:key="sex.value"
						:class="[ sex.class, formvalidate.sex === sex.value ? 'selected' : '' ]"
						@click="selectSex(sex.value)">
						<img
							:src="sex.icon"
							alt="">
						<p>{{ sex.label }}</p>
					</div>
				</div>
				<button
					class="button"
					name="submit"
					@click="postData">{{ $t('info.confirm') }}</button>
			</div>
		</div>
	</div>
</template>

<script>

import API_LIST from 'src/API_LIST';
import { mapGetters, mapActions, mapMutations } from 'vuex';
import Back from 'src/views/component/back';
import { formaturl } from 'src/utils/utils';
import { setTimeout } from 'timers';
// import { dateFormat } from 'vux';
import { isWechat, parseQueryString } from 'src/utils/helper';

const query_info = parseQueryString();


export default {

	name: 'Information',

	components: {
		back: Back,
	},

	data() {
		return {

			// isInWebApp: isInWebApp(),

			url_param: {}, // 用来存放网址参数

			formvalidate: {

				name: '',

				phone: '',

				sex: 1,

				age: 18,

			}, // 需要更新的用户信息表单

			sexs: [
				{
					value: 1,
					label: this.$t('info.male'),
					class: 'male',
					icon: require('src/assets/media/img/user/icon_nan.png'),
				},
				{
					value: 2,
					label: this.$t('info.female'),
					class: 'female',
					icon: require('src/assets/media/img/user/icon_nv.png'),
				},
			], // 性别数组

			focus: false,		// 是否聚焦

			normal_height: 0, // 手机屏幕正常高度

			key_map: {
				age: this.$t('info.age'),
			}, // key值映射表

			is_wechat: isWechat(),
		};
	},
	computed: {

		...mapGetters('userInfo', [
			'getUserInfo',
			'getAppid',
		]),

		...mapGetters('login', [
			'getUserPhone',
		]),

		...mapGetters('lang', [
			'getLang',
		]),

	},
	mounted() {
		this.normal_height = document.body.clientHeight;

		this.url_param = formaturl();

		this.initFormHeight();
		this.initUserInfo();
	},
	methods: {

		...mapActions('login', [
			'loginH5User',
		]),

		...mapMutations('login', [
			'setUserPhone',
		]),

		/**
		 * 生成年龄选择器的选项
		 * @return {Array} {年龄选项的数组}
		 */
		createAgeArray() {
			const ages = [];

			for (let i = 1; i <= 100; i += 1) {
				ages.push(i);
			}

			return ages;
		},

		/**
         * input输入框获得焦点时的事件
         * @return {undefined}
         */
		focusEvent() {
			// this.$refs.form_box.style.position = 'relative';

			this.focus = true;

			const self = this;

			window.addEventListener('resize', self.changeFormPosition);
		},

		/**
         * 改变元素定位的方法
         * @return {undefined}
         */
		changeFormPosition() {
			const client_height = document.documentElement.clientHeight || document.body.clientHeight;

			if (this.normal_height - client_height > 50) {
				this.focus = true;
			} else {
				this.focus = false;
			}
		},

		/**
         * input输入框失去焦点时的事件
         * @return {undefined}
         */
		blurEvent() {
			// this.$refs.form_box.style.position = 'inherit';

			this.focus = false;

			window.removeEventListener('resize', this.changeFormPosition);
		},

		/**
         * 初始化表单高度
         * @return {undefined}
         */
		initFormHeight() {
			const window_height = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;

			if (window_height) {
				this.$refs.form_box.style.height = `${0.9 * window_height}px`;
			}
		},

		/**
         * 初始化赋值用户信息数据
         * @return {undefined}
         */
		initUserInfo() {
			// const today = new Date();
			// const [t_year, t_months, t_Day] = today.toISOString().split('T').shift().split('-');
			// const before_year = `${t_year - 18}-${t_months}-${t_Day}`;

			this.formvalidate.name = this.getUserInfo.name || '';
			this.formvalidate.phone = this.getUserInfo.phone || '';
			this.formvalidate.sex = this.getUserInfo.sex || 1;

			this.formvalidate.age = this.getUserInfo.age || 18;
			// this.formvalidate.born_at = this.getUserInfo.born_at
			// 	? this.getUserInfo.born_at.replace(/\s+.+$/, '')
			// 	: dateFormat(new Date(before_year), 'YYYY-MM-DD');
		},

		/**
         * 选择出生年月
         * @return {undefined}
         */
		selectBorn() {
			const self = this;

			const current_time = this.formvalidate.born_at;

			this.$vux.datetime.show({
				minYear: '1900',
				cancelText: self.$t('info.select_cancel'),
				confirmText: self.$t('info.select_confirm'),
				format: 'YYYY-MM-DD',
				value: current_time,
				onConfirm(val) {
					self.formvalidate.born_at = val;
				},
			});
		},

		/**
         * 选择性别
         * @param  {number} value {性别的value值}
         * @return {undefined}
         */
		selectSex(value) {
			this.formvalidate.sex = value;
		},

		/**
         * 校验数据合法性
         * @return {Boolean} {true代表校验通过}
         */
		validateFormData() {
			const self = this;

			const keys = Object.keys(this.formvalidate);

			for (let i = 0; i < keys.length; i += 1) {
				const key = keys[i];

				const value = self.formvalidate[key];

				if (!value) {
					if (key !== 'name' && key !== 'phone') {
						return self.validateNoneValue(key);
					}
				} else if (key === 'phone') {
					// if (this.$i18n.locale === 'en') { // 英文环境下只校验数字
					// 	return self.isNumber(value);
					// }
					// return self.phoneValidate(value);
					return self.isNumber(value); // 只校验数字
				}
			}

			return true;
		},

		/**
         * 校验电话
         * @param  {string} phone {需要校验的电话值}
         * @return {Boolean} {true代表校验通过，反之不通过}
         */
		phoneValidate(phone) {
			const self = this;

			const tel_reg = /^1[356789]\d{9}$/;

			const phone_reg = /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;

			if (!tel_reg.test(phone)) {
				if (!phone_reg.test(phone)) {
					const toast = this.$createToast({
						type: 'warn',
						time: 2000,
						txt: self.$t('validation.tel'),
					});
					toast.show();
					return false;
				}

				return true;
			}

			return true;
		},

		/**
		 * 判断是否是数字
		 * @param {Number} str {手机号}
		 * @return {Boolean}
		 */
		isNumber(str) {
			return /^\d+$/.test(str);
		},

		/**
         * 校验空值
         * @param  {string} key {key值}
         * @return {Boolean} {true代表有值，反之没有}
         */
		validateNoneValue(key) {
			if (!this.formvalidate[key]) {
				const toast = this.$createToast({
					type: 'error',
					time: 1000,
					txt: `${this.key_map[key]}${this.$t('validation.null')}`,
				});
				toast.show();

				return false;
			}

			return true;
		},

		/**
		 * 校验数据是否和原始的一样
		 * @return {Boolean} {true代表没修改，反之修改}
		 */
		isSameData() {
			const keys = [...Object.keys(this.formvalidate)];

			return keys.every((key) => {
				if (!this.getUserInfo[key]) {
					return true;
				}
				return this.formvalidate[key] === this.getUserInfo[key];
			});
		},

		/**
         * 提交数据
         * @return {undefined}
         */
		postData() {
			// if (this.isSameData()) return this.backToPreviousPage();

			if (!this.validateFormData()) return;

			this.$http.post(API_LIST.UPDATE_USER_INFO, this.formatData())
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					// const is_collection_sacn_envent = !!this.url_param.favor_id;
					// if (this.url_param.scan_event_id && !is_collection_sacn_envent) {
					// 	setTimeout(() => {
					// 		wx.closeWindow();
					// 	}, 600);
					// }
				})
				.then(() => this.refreshUserInfo())
				.then((err) => {
					if (typeof err === 'string') return;
					// 成功提示
					const toast = this.$createToast({
						type: 'correct',
						time: 1000,
						txt: this.$t('common.submit_success'),
					});
					toast.show();
					this.redirectHomePage();
				})
				.catch((err) => {
					const toast = this.$createToast({
						type: 'error',
						time: 2000,
						txt: err.message || err.statusText,
					});
					toast.show();
				});
		},

		/**
         * 参数处理
         * @return {Object} {所需提交的参数}
         */
		formatData() {
			const param = {

				appid: this.getAppid,

				openid: this.getUserInfo.openid,

				name: this.formvalidate.name,

				phone: this.formvalidate.phone,

				sex: this.formvalidate.sex,

				// born_at: this.formvalidate.born_at,

				age: this.formvalidate.age,

			};

			if (this.$status.isScanMode()) { // this.$status.isScanMode()代表如果是扫码进入的
				param.scan_event_id = this.url_param.scan_event_id;
			}

			return param;
		},

		/**
         * 重新获取userInfo
         * @return {undefined}
         */
		refreshUserInfo() {
			if (this.$status.isAppidWxMode() || this.$status.isDebugMode()) {
				return this.$initData.handleUserinfoRequest();
			}
			this.setUserPhone(this.formvalidate.phone);
			const params = this.parseLoginParams();
			return this.loginH5User(params);
		},

		/**
		 * 解析重新登陆的参数
		 * @return {Object} {登录时需要的参数}
		 */
		parseLoginParams() {
			const { customer_id, scan_event_id, lang } = query_info;
			if (customer_id && scan_event_id) {
				return {
					customer_id,
					scan_event_id,
					language: lang || this.getLang,
					phone: this.getUserPhone,
				};
			} // 参数
			return null;
		},

		/**
         * 返回上一页
         * @return {undefined}
         */
		backToPreviousPage() {
			setTimeout(() => {
				this.$router.go(-1);
			}, 600);
		},

		/**
		 * 转跳至主页
		 * @param  {Number} delay {定时器的延时时间，默认为600ms}
		 * @return {undefined}
		 */
		redirectHomePage(delay = 600) {
			window.setTimeout(() => {
				this.$router.replace({ path: '/' });
			}, delay);
		},
	},
};
</script>

